package com.utooo.bid.controller;

import com.utooo.bid.model.Result;
import com.utooo.bid.service.DocumentIngestionService;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static com.utooo.bid.common.ResponseCode.FILE_PROCESSING_ERROR;

@RequestMapping("/api/rag")
@RequiredArgsConstructor
@RestController
public class RagController {

    private final DocumentIngestionService documentIngestionService;


    @PostMapping("/upload")
    public Result<String> uploadDocument(@RequestParam("file") MultipartFile file) {
        try {
            Path tempFile = Files.createTempFile("upload_", file.getOriginalFilename());
            file.transferTo(tempFile.toFile());
            Document document = FileSystemDocumentLoader.loadDocument(tempFile.toString());
            documentIngestionService.ingestDocument(document);
            Files.deleteIfExists(tempFile);
            return Result.success("文档已成功上传并处理");
        } catch (IOException e) {
            return Result.error(FILE_PROCESSING_ERROR.getCode(), "文档处理失败: " + e.getMessage());
        }
    }

}
